<?php
/**
 * @Author: liuhongbin
 * @Email: 514660094@qq.com
 * @Date: 2019-02-12 16:15:10
 * @Description:用户对应平台权限
 * @LastEditors: liuhongbin
 */

namespace app\controller\adminapi\addonAuth;


use app\common\model\platform\PlatformAppUser;
use app\common\controller\AdminController;
use app\common\model\addon\Addons;
use app\common\model\platform\Platform;
use app\common\model\platform\PlatformAddon;
use app\common\model\platform\PlatformApp;
use app\common\services\User;
use hiduoke\services\CloudServer;
use think\App;

class UserPlatformAddonAuth extends AdminController
{
    /**
     * @var Platform
     */
    private $Platform;
    /**
     * @var User
     */
    private $UserServices;
    /**
     * @var Addons
     */
    private $Addons;

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->Platform = new Platform();
        $this->UserServices = new User();
        $this->Addons = new Addons();
    }


    /**
     * 获取用户有权限的应用
     * @param int $plaid
     * @param int $exclude 0=全部，1=未添加的应用，2=已添加的应用
     * @return \think\response\Json
     */
    public function getUserAddonList()
    {
        $plaid = $this->request->post('plaid');
        $exclude = $this->request->post('exclude', 0);
        if (!$plaid) {
            return $this->error('请选择平台');
        }
        $uid = $this->request->post('uid', $this->userInfo['uid']);
        $platform = $this->Platform->where(['plaid' => $plaid])->find();
        //自己的平台
        if ($platform->uid == $uid) {
            $addons = $this->UserServices->getUserAllAddons($uid); //获取可添加的平台
            $useful_addon_names = [];
            if ($exclude > 0) {
                //过滤已经添加了的应用
                $used_addon_names = [];
                $used_platform_addon_list = PlatformAddon::where(['plaid' => $plaid])->field(['addon_name'])->select();//已经添加了的应用列表
                $all_useful = (new PlatformAddon())->getCustomerUsefulAddonNames();
                foreach ($used_platform_addon_list as $key => $value) {
                    //过滤已经添加了的平台列表
                    if (isset($addons[$value['addon_name']])) unset($addons[$value['addon_name']]);
                    $used_addon_names[] = $value['addon_name'];
                }
                //所有可用的应用标识与用户可用的用户取交集
                $useful_addon_names = array_intersect(array_keys($addons), $all_useful);
                if ($exclude == 2) {
                    //获取已经使用的
                    $useful_addon_names = $used_addon_names;
                }
            }

            $data = $this->Addons->getPageListModel()->whereIn('name', $useful_addon_names)->where(['type' => $platform['type']])->select();
            $count = $this->Addons->getPageListModel([], false)->whereIn('name', $useful_addon_names)->where(['type' => $platform['type']])->count();
            return $this->success($count, $data);
        } else {
            return $this->success('', []);
        }
    }


    public function getUserAddonList2()
    {
        $plaid = get_plaid();
        $platform = (new Platform())->where(['plaid' => $plaid])->find();
        if (!$platform) {
            return $this->error('平台不存在');
        }
        $size = input('size');
        $uid = $this->request->post('uid', $this->userInfo['uid']);
        if (!$platform->uid == $uid) {
            return $this->success('子账号');
        }
        // 已添加的应用
        $platform_addons = (new PlatformAddon())->where(['plaid' => $plaid])->select(); // 已添加

        $platform_addon_names = [];

        foreach ($platform_addons as $key => $value) {
            $platform_addon_names[] = $value['addon_name'];
        }
        $row = (new Addons())->where(['type' => $platform['type']])->whereNotIn('name', $platform_addon_names)->paginate($size);
        // 获取云端可用的应用数据
        $cloud_addon = (new CloudServer())->getSiteAddonTokenCount();
        // 用户有权限的应用
        $addons = $this->UserServices->getUserAllAddons($uid); //获取可添加的平台
        $data = $row->items();
        $count = $row->total();
        foreach ($data as $key => $value) {
            // 判断是否有云端数据
            if (isset($cloud_addon[$value['name']])) {
                // 云端数据
                $cloud_count = $cloud_addon[$value['name']];
                if ($cloud_count['surplus_count'] > 0) {
                    $data[$key]['cloud_available'] = true;
                } else {
                    $data[$key]['cloud_available'] = false;
                }
            } else {
                $data[$key]['cloud_available'] = true;
            }
            // 判断可添加平台
            if (isset($addons[$value['name']])) {
                // 可添加的平台
                $data[$key]['available'] = true;
            } else {
                $data[$key]['available'] = false;
            }
        }
        return $this->success($count, $data);
    }

    /**
     * 获取用户有权限的小程序列表
     * @param int $plaid
     * @param int $exclude 0=全部，1=未添加的应用，2=已添加的应用
     * @return \think\response\Json
     */
    public function getUserAddonAppList()
    {
        $plaid = $this->request->post('plaid');
        $exclude = $this->request->post('exclude', 0);
        if (!$plaid) {
            return $this->error('请选择平台');
        }
        $uid = $this->request->post('uid', $this->userInfo['uid']);
        $platform = $this->Platform->where(['plaid' => $plaid])->find();
        //自己的平台
        if ($platform->uid == $uid) {
            $addons = $this->UserServices->getUserAllAddons($uid); //获取可添加的平台
            $useful_addon_names = [];
            if ($exclude != 0) {
                //过滤已经添加了的应用
                $used_addon_names = [];
                $used_platform_addon_list = PlatformAddon::where(['plaid' => $plaid])->field(['addon_name'])->select();//已经添加了的应用列表
                // 获取云端可用的应用数据
                $all_useful = (new PlatformAddon())->getCustomerUsefulAddonNames();
                foreach ($used_platform_addon_list as $key => $value) {
                    //过滤已经添加了的平台列表
                    if (isset($addons[$value['addon_name']])) unset($addons[$value['addon_name']]);
                    $used_addon_names[] = $value['addon_name'];
                }
                //所有可用的应用标识与用户可用的用户取交集
                $useful_addon_names = array_intersect(array_keys($addons), $all_useful);
            }
            if ($exclude == 2) {
                //获取已经使用的
                $useful_addon_names = $used_addon_names;
            }
            // 获取小程序剩余添加次数
            $data = $this->Addons->getPageListModel()->whereIn('name', $useful_addon_names)->where(['type' => $platform['type']])->select();
            foreach ($data as $key => $value) {
                // 用户使用次数
                $app_use_count = (new PlatformApp())->where(['uid' => $uid, 'addon_name' => $value['name']])->count();
                // 用户可用次数
                $app_count = (new PlatformAppUser())->where(['uid' => $uid, 'addon_name' => $value['name']])->find()['count'] ?? 0;
                $data[$key]['app_use_count'] = $app_use_count;
                $data[$key]['app_count'] = $app_count;
                $data[$key]['count'] = $app_count - $app_use_count;
            }
            $count = $this->Addons->getPageListModel([], false)->whereIn('name', $useful_addon_names)->where(['type' => $platform['type']])->count();
            return $this->success($count, $data);
        } else {
            return $this->success();
        }
    }

    /**
     * 获取小程序应用列表
     * Create by :  刘泓宾<514660094@qq.com>
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getUserAddonAppList2()
    {
        $plaid = get_plaid();
        $platform = (new Platform())->where(['plaid' => $plaid])->find();
        if (!$platform) {
            return $this->error('平台不存在');
        }
        $size = input('size');
        $uid = $this->request->post('uid', $this->userInfo['uid']);
        if (!$platform->uid == $uid) {
            return $this->success();
        }
        $row = (new Addons())->where(['type' => $platform['type']])->paginate($size);
        // 获取云端可用的应用数据
        $cloud_addon = (new CloudServer())->getSiteAddonTokenCount();
        // 用户有权限的应用
        $addons = $this->UserServices->getUserAllAddons($uid); //获取可添加的平台

        $data = $row->items();
        $count = $row->total();
        foreach ($data as $key => $value) {
            // 判断是否有云端数据
            if (isset($cloud_addon[$value['name']])) {
                // 云端数据
                $cloud_count = $cloud_addon[$value['name']];
                if ($cloud_count['surplus_count'] > 0) {
                    $data[$key]['cloud_available'] = true;
                } else {
                    $data[$key]['cloud_available'] = false;
                }
            } else {
                $data[$key]['cloud_available'] = true;
            }
            // 判断可添加平台
            if (isset($addons[$value['name']])) {
                // 可添加的平台
                $data[$key]['available'] = true;
            } else {
                $data[$key]['available'] = false;
            }
            // 用户使用次数
            $app_use_count = (new PlatformApp())->where(['uid' => $uid, 'addon_name' => $value['name']])->count();
            // 用户可用次数
            $app_count = (new PlatformAppUser())->where(['uid' => $uid, 'addon_name' => $value['name']])->find()['count'] ?? 0;
            $data[$key]['app_use_count'] = $app_use_count;
            $data[$key]['app_count'] = $app_count;
            $data[$key]['count'] = $app_count - $app_use_count;
        }
        return $this->success($count, $data, [$cloud_addon, $data, $addons]);
    }
}
